from flask import Flask, request, jsonify
from flask_cors import CORS
import os
import base64
import cv2
import numpy as np
from datetime import datetime
from db import Database
from scan import scan_image
import traceback

app = Flask(__name__)
CORS(app)
db = Database()

# 创建保存扫描图像的目录
SCANNED_IMAGES_DIR = 'scanned_images'
os.makedirs(SCANNED_IMAGES_DIR, exist_ok=True)

# 原有的上传接口（保持不变）
@app.route('/upload', methods=['POST'])
def upload_image():
    print("=== 开始处理上传请求 ===")
    files = request.files.getlist('file')
    print(f"接收到 {len(files)} 个文件")
    results = []

    for i, file in enumerate(files):
        print(f"处理文件 {i + 1}: {file.filename}")
        try:
            # 读取文件数据
            image_data = file.read()
            print(f"文件大小: {len(image_data)} 字节")

            if len(image_data) == 0:
                raise Exception("文件为空")

            # 转换为Base64
            base64_image = base64.b64encode(image_data).decode('utf-8')
            print("原始图像Base64编码完成")

            # 进行扫描处理
            print("开始扫描处理...")
            scanned_image = scan_image(image_data)
            print("扫描处理完成")

            scanned_base64 = base64.b64encode(scanned_image).decode('utf-8')
            print("扫描图像Base64编码完成")

            # 插入数据库
            upload_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            print(f"准备插入数据库，时间: {upload_time}")

            db.insert_image(base64_image, scanned_base64, upload_time)
            print("数据库插入成功")

            results.append({
                'filename': file.filename,
                'upload_time': upload_time,
                'status': '处理完成',
                'id': db.get_last_insert_id()  # 获取插入的ID
            })
            print(f"文件 {file.filename} 处理完成")

        except Exception as e:
            error_msg = str(e)
            print(f"❌ 文件 {file.filename} 处理失败: {error_msg}")
            print(f"详细错误信息: {traceback.format_exc()}")
            results.append({
                'filename': file.filename,
                'upload_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'status': f'处理失败: {error_msg}'
            })

    print(f"=== 上传处理完成，共处理 {len(results)} 个文件 ===")
    return jsonify({'results': results}), 200

# 获取图像列表接口
# 获取图像列表接口
@app.route('/images', methods=['GET'])
def get_images():
    try:
        images = db.get_images()
        print(f"获取到 {len(images)} 条图像记录")
        return jsonify({'images': images}), 200
    except Exception as e:
        print(f"获取图像列表失败: {str(e)}")
        return jsonify({'error': str(e)}), 500


# 新增：保存扫描图像到本地的接口
@app.route('/save-scanned/<int:image_id>', methods=['POST'])
def save_scanned_image(image_id):
    """
    将指定ID的扫描图像保存到本地
    """
    try:
        # 从数据库获取图像数据
        image_record = db.get_image_by_id(image_id)
        print(f"获取到图像记录: {image_record}")

        if not image_record:
            return jsonify({'error': '图像不存在'}), 404

        # 确保是字典类型
        if not isinstance(image_record, dict):
            return jsonify({'error': '图像数据格式错误'}), 500

        # 获取扫描后的图像数据
        scanned_base64 = image_record.get('scanned_image')
        if not scanned_base64 or not scanned_base64.strip():
            return jsonify({'error': '该图像没有扫描数据'}), 400

        # 解码Base64数据
        try:
            image_data = base64.b64decode(scanned_base64)
        except Exception as e:
            return jsonify({'error': f'Base64解码失败: {str(e)}'}), 500

        # 生成文件名
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        output_filename = f"scanned_image_{image_id}_{timestamp}.jpg"
        output_path = os.path.join(SCANNED_IMAGES_DIR, output_filename)

        # 保存到本地
        with open(output_path, 'wb') as f:
            f.write(image_data)

        return jsonify({
            'success': True,
            'message': f'扫描图像已保存到: {output_path}',
            'file_path': output_path
        }), 200

    except Exception as e:
        print(f"❌ 保存失败: {str(e)}")
        return jsonify({'error': f'保存失败: {str(e)}'}), 500


# 新增：批量保存所有扫描图像到本地
# 修改 save_all_scanned_images 方法
@app.route('/save-all-scanned', methods=['POST'])
def save_all_scanned_images():
    """
    将所有扫描图像保存到本地
    """
    try:
        # 获取所有图像记录
        images = db.get_images_with_data()
        print(f"从数据库获取到 {len(images) if images else 0} 条记录")

        if not images or len(images) == 0:
            return jsonify({'error': '没有图像数据'}), 404

        saved_count = 0
        failed_count = 0
        saved_files = []

        for image_record in images:
            try:
                # 确保 image_record 是字典类型
                if not isinstance(image_record, dict):
                    failed_count += 1
                    continue

                scanned_base64 = image_record.get('scanned_image')
                if scanned_base64 and scanned_base64.strip():
                    # 解码并保存
                    image_data = base64.b64decode(scanned_base64)

                    # 生成文件名
                    image_id = image_record.get('id', 'unknown')
                    upload_time = image_record.get('upload_time')
                    if upload_time:
                        # 格式化时间戳
                        if isinstance(upload_time, str):
                            timestamp = upload_time.replace(':', '').replace('-', '').replace(' ', '_')
                        else:
                            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                    else:
                        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')

                    output_filename = f"scanned_image_{image_id}_{timestamp}.jpg"
                    output_path = os.path.join(SCANNED_IMAGES_DIR, output_filename)

                    # 保存到本地
                    with open(output_path, 'wb') as f:
                        f.write(image_data)

                    saved_files.append(output_path)
                    saved_count += 1
                    print(f"✅ 保存成功: {output_path}")
                else:
                    print(f"⚠️  图像 {image_record.get('id')} 没有扫描数据")
                    failed_count += 1
            except Exception as e:
                print(f"❌ 保存图像时出错: {str(e)}")
                failed_count += 1
                continue

        if saved_count == 0 and failed_count > 0:
            return jsonify({
                'success': False,
                'message': f'没有成功保存任何图像，失败 {failed_count} 张',
                'saved_count': 0,
                'failed_count': failed_count,
                'saved_files': []
            }), 200

        return jsonify({
            'success': True,
            'message': f'成功保存 {saved_count} 张图像，失败 {failed_count} 张',
            'saved_count': saved_count,
            'failed_count': failed_count,
            'saved_files': saved_files
        }), 200

    except Exception as e:
        print(f"❌ 批量保存失败: {str(e)}")
        return jsonify({'error': f'批量保存失败: {str(e)}'}), 500


# 新增：直接上传并保存扫描结果（用于快速验证）
@app.route('/upload-and-save', methods=['POST'])
def upload_and_save():
    """
    上传图像并立即保存扫描结果到本地（用于快速验证）
    """
    files = request.files.getlist('file')
    results = []

    for file in files:
        try:
            image_data = file.read()

            # 进行扫描处理
            scanned_image_data = scan_image(image_data)

            # 生成文件名并保存到本地
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            original_filename = os.path.splitext(file.filename)[0]
            output_filename = f"{original_filename}_scanned_{timestamp}.jpg"
            output_path = os.path.join(SCANNED_IMAGES_DIR, output_filename)

            # 保存扫描后的图像
            with open(output_path, 'wb') as f:
                f.write(scanned_image_data)

            results.append({
                'filename': file.filename,
                'saved_path': output_path,
                'status': '处理并保存成功'
            })

        except Exception as e:
            results.append({
                'filename': file.filename,
                'error': str(e),
                'status': '处理失败'
            })

    return jsonify({'results': results}), 200

# 添加调试接口
@app.route('/debug/database', methods=['GET'])
def debug_database():
    """
    调试接口：检查数据库连接和数据
    """
    try:
        images = db.get_images_with_data()
        return jsonify({
            'success': True,
            'total_images': len(images) if images else 0,
            'images': images if images else [],
            'database_status': 'connected'
        }), 200
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e),
            'database_status': 'error'
        }), 500


if __name__ == '__main__':
    app.run(debug=True, port=5000)